package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanTable;

import beans.Bookmark;
import beans.User;

import model.BookmarkDAO;
import model.Model;
import model.UserDAO;

/*
 *  Course: S09-15437 - WEB APPLICATION DEVELOPMENT 
 * 	Name: Jiale Huang
 * 	Andrew ID: jialeh
 * 	Date: 2/23/2009
 *  Assignment: Hw4
 */


public class Controller extends HttpServlet {

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		Model model = new Model(getServletConfig());
		
        Action.add(new AddBookmarkAction(model));
        Action.add(new AddCountClickAction(model));
        Action.add(new ChangePwdAction(model));
        Action.add(new DelBookmarkAction(model));
        Action.add(new ListBookmarkAction(model));
        Action.add(new LoginAction(model));
        Action.add(new LogoutAction(model));
        Action.add(new RegisterAction(model));
        Action.add(new ManageAction(model));
        Action.add(new CheckEmailAction(model));
        Action.add(new DisplayTagAction(model));
	}
	
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        String nextPage = performTheAction(request);
        sendToNextPage(nextPage,request,response);
	}

	private String performTheAction(HttpServletRequest request) {
        HttpSession session     = request.getSession(true);
        String      servletPath = request.getServletPath();
        User        user = (User) session.getAttribute("user");
        String      action = getActionName(servletPath);

        if(action.equals("checkEmail.do")){
        	return Action.perform("checkEmail.do", request);
        }
        
        if(action.equals("displayTag.do")){
        	return Action.perform("displayTag.do", request);        
        }
        
        if (action.equals("register.do") || action.equals("login.do")) {
        	// Allow these actions without logging in
			return Action.perform(action,request);
        }
        
        if(user == null){
        
	        if (action.equals("start") || action.equals("listBookmarks.do")) {
	        	// If the user hasn't logged in, direct him to the login page
				return Action.perform("listBookmarks.do",request);
	        } else if(action.equals("addClick.do")){
	        	
	        	return Action.perform("addClick.do", request);	                
	        }else{
	        
	        	return Action.perform("login.do", request);
	        }
        
        }
        
        if (action.equals("start")) {
        	// If he's logged in but back at the /start page, send him to manage his pics
			return Action.perform("listBookmarks.do",request);
        }
       
		return Action.perform(action,request);
        
	}
	
	private void sendToNextPage(String nextPage, HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
    	// System.out.println("nextPage="+nextPage);
    	
    	if (nextPage == null) {
    		response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getServletPath());
    		return;
    	}
    	
    	if (nextPage.substring(0, 5).equals("[out]")) {
        	nextPage = nextPage.substring(5);
			response.sendRedirect("http://" + nextPage);
			return;
    	}
    	
    	if (nextPage.substring(0,6).equals("[ajax]")){
    		response.getWriter().println(nextPage.substring(6));
    		return;
    	}
    	
    	if (nextPage.substring(0,5).equals("[xml]")){
    		response.setContentType("text/xml");
    		response.getWriter().println(nextPage.substring(5));
    		return;
    	}

    	if (nextPage.charAt(0) == '/') {
			String host  = request.getServerName();
			String port  = ":"+String.valueOf(request.getServerPort());
			if (port.equals(":80")) port = "";
			response.sendRedirect("http://"+host+port+nextPage);
			return;
    	}
    	

    	
   		RequestDispatcher d = request.getRequestDispatcher("/"+nextPage);
   		d.forward(request,response);		
	}

	private String getActionName(String path) {
    	// We're guaranteed that the path will start with a slash
        int slash = path.lastIndexOf('/');
		return path.substring(slash+1);
	}
	
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
}
